package entity

import (
	"fmt"
	"time"

	"gorm.io/gorm"
	"shqsoft.cn/pas3ui/base"
)

//对私储蓄存款认定分户情况
type IndiLoanPl struct {
	ID          int       `gorm:"AUTO_INCREMENT;primary_key;column:ID"`
	ACID        *int      `gorm:"column:ACID"` //帐户序号
	EVNO        string    `gorm:"column:EVNO"`
	KHMC        string    `gorm:"column:KHMC"`
	IDNO        string    `gorm:"column:IDNO"`
	EMID1       *int      `gorm:"column:EMID1"`
	EMNO1       string    `gorm:"column:EMNO1"`
	ZB1         float64   `gorm:"column:ZB1"`
	EMID2       *int      `gorm:"column:EMID2"`
	EMNO2       string    `gorm:"column:EMNO2"`
	ZB2         float64   `gorm:"column:ZB2"`
	EMID3       *int      `gorm:"column:EMID3"`
	EMNO3       string    `gorm:"column:EMNO3"`
	ZB3         float64   `gorm:"column:ZB3"`
	DSDT        time.Time `gorm:"column:DSDT"` //分户日期
	DSEM        *int      `gorm:"column:DSEM"`
	CLJG        string    `gorm:"column:CLJG"` //导入结果
	ISTZ        string    `gorm:"column:ISTZ"` //批量认定处理方式：0 处理未分配 1调整已分配
	ISTZCaption string    `gorm:"-"`
}

//TableName 对私储蓄存款认定分户情况
func (IndiLoanPl) TableName() string {
	return "T_INDI_LOAN_PL"
}

func (i *IndiLoanPl) BeforeSave(tx *gorm.DB) (err error) {
	bdate, err := base.GetBackDATE()
	if err != nil {
		return
	}
	if i.DSDT.Unix() < bdate.Unix() {
		err = fmt.Errorf("分户日期不能小于最早可追溯日期，最大追溯日期为【" + bdate.Format("2006-01-02") + "】")
		return
	}
	var count int
	base.CHDB.Raw("SELECT ID FROM T_INDI_LOAN WHERE EVNO = ?", i.EVNO).Row().Scan(&i.ACID)
	base.CHDB.Raw("SELECT COUNT(*) FROM T_INDI_LOAN WHERE EVNO = ? AND (CUNM = ? OR CUNM='')", i.EVNO, i.KHMC).Row().Scan(&count)
	if count == 0 {
		err = fmt.Errorf("借据号%s与客户名称%s不匹配！", i.EVNO, i.KHMC)
		return
	}
	//判断是否重复导入
	if i.ID == 0 {
		tx.Raw(`SELECT COUNT(*) FROM "T_INDI_LOAN_PL" WHERE "ACID"=?`, i.ACID).Row().Scan(&count)
		if count > 0 {
			err = fmt.Errorf("客户名称:%s,不能重复导入！", i.KHMC)
			return
		}
	}
	sum := i.ZB1 + i.ZB2 + i.ZB3
	if sum != 100 {
		err = fmt.Errorf("占比之和必须为100！")
		return
	}
	strSql := `SELECT "ID" FROM "T_SysUser" WHERE "SysUserID" =?`
	err = tx.Raw(strSql, i.EMNO1).Row().Scan(&i.EMID1)
	if err != nil {
		err = fmt.Errorf("员工工号1:%s在系统中没有找到！", i.EMNO1)
		return
	}
	if i.ZB2 > 0 {
		err = tx.Raw(strSql, i.EMNO2).Row().Scan(&i.EMID2)
		if err != nil {
			err = fmt.Errorf("员工工号2:%s在系统中没有找到！", i.EMNO2)
			return
		}
	}
	if i.ZB3 > 0 {
		err = tx.Raw(strSql, i.EMNO3).Row().Scan(&i.EMID3)
		if err != nil {
			err = fmt.Errorf("员工工号3:%s在系统中没有找到！", i.EMNO3)
			return
		}
	}
	if i.ISTZ == "0" {
		tx.Raw(`SELECT COUNT(*) FROM "T_INDI_LOAN_DIVI" WHERE "ACID"=?`, i.ACID).Row().Scan(&count)
		if count > 0 {
			i.CLJG = "已存在认定关系"
		}
	}
	if i.CLJG == "" {
		i.CLJG = "成功"
	}
	return
}

func (i *IndiLoanPl) AfterFind(tx *gorm.DB) (err error) {
	if i.ISTZ == "0" {
		i.ISTZCaption = "批量处理未分配的个贷客户"
	} else if i.ISTZ == "1" {
		i.ISTZCaption = "批量调整已分配的个贷客户"
	}
	return
}

//IndiLoanAfterImport 导入后执行分户处理
func IndiLoanAfterImport(tx *gorm.DB, params map[string]string) (err error) {
	var sqlstr string
	if base.AppConf.Database.Mysql != "" {
		sqlstr = `UPDATE "T_INDI_LOAN_DIVI" A,"T_INDI_LOAN_PL" B
		SET "WODT"=B."DSDT","ISWO"=CASE WHEN A."DSDT"<B."DSDT" THEN 0 ELSE 1 END
		WHERE B."CLJG" = '成功' AND A."ACID"=B."ACID" AND A."ISWO"=0 AND (A."WODT" IS NULL OR A.WODT>B."DSDT")`
	} else {
		sqlstr = `UPDATE "T_INDI_LOAN_DIVI" A SET "WODT"=B."DSDT","ISWO"=CASE WHEN A."DSDT"<B."DSDT" THEN 0 ELSE 1 END
		from "T_INDI_LOAN_PL" B
		WHERE B."CLJG" = '成功' AND A."ACID"=B."ACID" AND A."ISWO"=0 AND (A."WODT" IS NULL OR A."WODT">B."DSDT")`
	}
	err = tx.Exec(sqlstr).Error
	if err != nil {
		tx.Rollback()
		return
	}
	sqlstr = `INSERT INTO "T_INDI_LOAN_DIVI"("ACID","EMID","DSVL","DSDT","DSEM")
	SELECT DISTINCT "ACID","EMID","DSVL","DSDT","DSEM" 
	FROM (SELECT "ACID","EMID1" "EMID","ZB1"/100 "DSVL","DSDT","DSEM" FROM "T_INDI_LOAN_PL" WHERE "CLJG" = '成功'
	UNION ALL
	SELECT "ACID","EMID2" "EMID","ZB2"/100 "DSVL","DSDT","DSEM" FROM "T_INDI_LOAN_PL"
	WHERE "CLJG" = '成功' AND "EMID2" IS NOT NULL
	UNION ALL
	SELECT "ACID","EMID3" "EMID","ZB3"/100 "DSVL","DSDT","DSEM" FROM "T_INDI_LOAN_PL"
	WHERE "CLJG" = '成功' AND "EMID3" IS NOT NULL) A`
	err = tx.Exec(sqlstr).Error
	if err != nil {
		tx.Rollback()
		return
	}
	tx.Commit()
	return
}

func IndiLoanPlEF() base.EntityFunc {
	return func() interface{} {
		entity := IndiLoanPl{}
		return &entity
	}
}
func IndiLoanPlESF() base.EntitiesFunc {
	return func() interface{} {
		var entities []IndiLoanPl
		return &entities
	}
}

func init() {
	base.DaoPoolObj.Put("IndiLoanPl", base.NewDefaultDao(IndiLoanPlEF(), IndiLoanPlESF(), nil, "my"))
	base.SetAfterCallBack("IndiLoanPl", IndiLoanAfterImport)
}
